<script setup>
import { nextTick, ref } from "vue"

const props = defineProps({
  modelValue: String
})
const emit = defineEmits(["update:modelValue"])

const inputValue = ref("")
const dynamicTags = ref(props.modelValue ? props.modelValue.split(",") : [])
const inputVisible = ref(false)
const InputRef = ref()

const handleClose = tag => {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
  emit("update:modelValue", dynamicTags.value.join(","))
}

const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value.input.focus()
  })
}

const handleInputConfirm = () => {
  if (inputValue.value) {
    dynamicTags.value.push(inputValue.value)
    emit("update:modelValue", dynamicTags.value.join(","))
  }
  inputVisible.value = false
  inputValue.value = ""
}
</script>

<template>
  <el-tag v-for="tag in dynamicTags" :key="tag" closable :disable-transitions="false" @close="handleClose(tag)">
    {{ tag }}
  </el-tag>
  <el-input v-if="inputVisible" ref="InputRef" v-model="inputValue" size="small" @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
  <el-button v-else size="small" @click="showInput"> + 添加值 </el-button>
</template>

<style lang="scss" scoped>
.el-tag {
  margin: 0 6px 6px 0;
}
.el-input {
  width: 50px;
}
@media screen and (max-width: 375px), screen and (max-width: 414px) {
  .el-tag {
    margin: 0 4px 4px 0;
    :deep(.el-tag__content) {
      max-width: 5vw;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }
}
</style>
